import Vue from 'vue'
import axios from 'axios'
import router from '../router'
import Cookies from "js-cookie";
import {
  Dialog
} from 'vant';
import {
  getToken
} from '@/utils/auth'
// //设置axios为form-data
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.transformRequest = [function (data) {
//   let ret = ''
//   for (let it in data) {
//     ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
//   }
//   return ret
// }]
// 创建一个axios实例
const service = axios.create({

  baseURL: '/', //写死
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 300000, // request timeout

})

// 请求拦截器
service.interceptors.request.use(
  config => {
// console.log(service,222222)
    // config.baseURL = 'frankliu'
    // 在发送请求之前做一些事情
    if (window.sessionStorage.getItem('Token')) {
      // 让每个请求都携带 token
      // ['X-Token'] 是一个自定义标题键
     
      config.headers['X-Token'] = getToken()
    }

    config.headers['X-Token'] =  Cookies.get("xtoken")

     window.sessionStorage.setItem('baseURL',config.baseURL)
     console.log(config, 2222222222222)
    return config
  },
  error => {
    console.log(error, 'service interceptors request error') // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    console.log(response)
    if (res.code == '50014') {
      Dialog.alert({
        title: '错误',
        message: res.msg,
      }).then(() => {
        router.push({
          path: "/"
        });
      });
    }
    return res;
    // 如果自定义代码不是20000，则判断为错误。
  },
  error => {
    console.log('err' + error) // for debug

    return Promise.reject(error)
  }
)

export default service
